<template>
  <div class="user-container">
    <div style="text-align: start">
      <a-button @click="add">新建用户</a-button>
    </div>
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="dataSource"
      rowKey="id"
      :pagination="false"
      style="height: 700px; margin-top: 20px; overflow: hidden"
    >
      <div slot="action" slot-scope="text, record">
        <a @click="edit(record)" style="margin-right: 8px"> 编辑 </a>
        <a-divider type="vertical" />
        <a @click="resetPassword(record)" style="margin-right: 8px">
          重置密码
        </a>
        <a-divider type="vertical" />
        <a-popconfirm
          title="确定删除吗?"
          @confirm="deleteUser(record)"
          ok-text="删除"
          cancel-text="取消"
        >
          <a style="margin-right: 8px"> 删除 </a>
        </a-popconfirm>
      </div>
    </a-table>
    <div class="pagination">
      <a-pagination
        :defaultPageSize="pagination.pageSize"
        :current="pagination.current"
        show-quick-jumper
        :total="pagination.total"
        show-less-items
        @change="onPageChange"
      />
    </div>
    <a-modal
      :confirm-loading="confirmLoading"
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="800"
    >
      <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="用户名">
          <a-input
            :disabled="type == 'edit'"
            placeholder="请输入用户名"
            v-decorator="[
              'userId',
              {
                rules: [{ required: true, message: '请输入用户名!' }],
                initialValue: form.userId,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input
            placeholder="请输入昵称"
            v-decorator="[
              'userName',
              {
                rules: [{ required: true, message: '请输入昵称!' }],
                initialValue: form.userName,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input
            placeholder="请输入身份证号"
            v-decorator="[
              'idNumber',
              {
                rules: [
                  { required: true, message: '' },
                  { validator: validatorIdCardNumber },
                ],
                initialValue: form.idNumber,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="银行卡号">
          <a-input
            placeholder="请输入银行卡号"
            v-decorator="[
              'bankCardNumber',
              {
                rules: [
                  { required: true, message: '' },
                  { validator: validatorBankCardNumber },
                ],
                initialValue: form.bankCardNumber,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {
  getUserList,
  addUser,
  editUser,
  resetPassword,
  deleteUser,
} from '@/api/user';
const columns = [
  {
    title: '账号',
    dataIndex: 'userId',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'userName',
    align: 'center',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
];
export default {
  name: 'user',
  components: {},
  data() {
    return {
      form: this.$form.createForm(this, {
        userId: undefined,
        userName: undefined,
        idNumber: undefined,
        bankCardNumber: undefined,
      }),
      loading: true,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      parames: {},
      columns,
      title: '新建用户',
      visible: false,
      editId: '',
      confirmLoading: false,
      type: 'add',
    };
  },
  created() {
    this.getData();
  },
  computed: {},
  methods: {
    getData() {
      this.loading = true;
      let request = { ...this.parames };
      request.currentPage = this.pagination.current;
      request.pageSize = this.pagination.pageSize;
      getUserList(request).then((response) => {
        this.dataSource = response.data.list;
        this.pagination.total = response.data.count;
        this.loading = false;
      });
    },
    onPageChange(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.getData();
    },
    edit(record) {
      console.log(record);
      this.type = 'edit';
      this.title = '编辑用户';
      this.editId = record.id;
      this.form.userName = record.userName;
      this.form.userId = record.userId;
      this.form.idNumber = record.idNumber;
      this.form.bankCardNumber = record.bankCardNumber;
      this.visible = true;
    },
    add() {
      this.type = 'add';
      this.title = '新建用户';
      this.visible = true;
    },
    handleCancel() {
      this.initForm();
      this.visible = false;
    },
    handleOk(e) {
      e.preventDefault();
      const { type } = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          let request = { ...values, id: this.editId };
          console.log(request);
          if (type === 'add') {
            addUser(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          } else {
            editUser(request).then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.$message.success(response.message);
                this.getData();
                this.visible = false;
              } else {
                this.$message.error(response.message);
              }
              this.confirmLoading = false;
              this.initForm();
            });
          }
        }
      });
    },
    initForm() {
      Object.keys(this.form.getFieldsValue()).forEach((key) => {
        this.form[key] = undefined;
      });
    },
    resetPassword(record) {
      resetPassword({ id: record.id }).then((response) => {
        console.log(response);
        if (response.code == 200) {
          this.$message.success('重置成功');
        } else {
          this.$message.error(response.message);
        }
      });
    },
    deleteUser(record) {
      deleteUser([record.id]).then((response) => {
        if (response.code == 200) {
          this.getData();
          this.$message.success('删除成功');
        } else {
          this.$message.error(response.message);
        }
      });
    },
    validatorIdCardNumber(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入身份证号!'));
      } else {
        if (
          !/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/.test(
            value
          )
        ) {
          callback(new Error('身份证号格式不正确!'));
        } else {
          callback();
        }
      }
    },
    validatorBankCardNumber(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入银行卡号!'));
      } else {
        if (!/^([1-9]{1})(\d{15}|\d{18})$/.test(value)) {
          callback(new Error('银行卡号格式不正确!'));
        } else {
          callback();
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.user-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .pagination {
    height: 30px;
    line-height: 30px;
    width: 100%;
    text-align: right;
  }
}
</style>
